package org.elsfs.framework.event.support;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.elsfs.framework.event.Subscribe;
import org.elsfs.framework.lang.ClassUtils;

/**
 * 注解{@link Subscribe}事件监听器读取器.
 *
 * @author zeng
 * @since 0.0.1
 */
public class AnnotationEventListenerResolver implements EventListenerResolver {

  /** 读取的注解. */
  private final Class<? extends Annotation> annotationClass;

  /** 默认构造器 读取的是{@link Subscribe}注解标注的方法或者类. */
  public AnnotationEventListenerResolver() {
    this(Subscribe.class);
  }

  /**
   * 构造器.
   *
   * @param annClass 注解
   */
  public AnnotationEventListenerResolver(final Class<? extends Annotation> annClass) {
    this.annotationClass = annClass;
  }

  /**
   * 获取监听器.
   *
   * @param instance 实例
   * @return 监听器列表
   */
  @Override
  public List<EventListener> getEventListeners(final Object instance) {
    if (instance == null) {
      return Collections.emptyList();
    }
    List<Method> methods =
        ClassUtils.getAnnotatedMethods(instance.getClass(), getAnnotationClass());
    if (methods == null || methods.isEmpty()) {
      return Collections.emptyList();
    }

    List<EventListener> listeners = new ArrayList<>(methods.size());

    for (Method m : methods) {
      listeners.add(new SingleArgumentMethodEventListener(instance, m));
    }
    return listeners;
  }

  /**
   * 获取注解.
   *
   * @return 默认返回 {@link Subscribe}.
   */
  public Class<? extends Annotation> getAnnotationClass() {
    return annotationClass;
  }
}
